import ImageModel from '../../models/Image'
import config from "../../config/config";
import Crypt from "../../utils/Crypt";
import PageModel from "../../models/Page";
const model = new ImageModel()

const pageModel = new PageModel()

Page({
  data: {
    swiper: [],
    middle: '',
    column1_title: '',
    column2_title: '',
    column1: [],
    column2: [],
    baseUrl: '',
    column1_index: 0,
    column2_index: 0,
    click1: false,
    click2: false,
    nav: []
  },
  onLoad: function (options) {
    this.setData({
      baseUrl: config.app_base_url
    })
    this.fetch()
    this.nav()
  },

  nav() {
    pageModel.getHome().then(response => {
      let { data } = response
      data = Crypt.parse(data)
      this.setData({ ...data })
      // console.log(this.data.nav)
    })
  },


  fetch() {
    model.homePage().then(data => {
      // console.log(data)
      const { swiper, middle, column1_title, column2_title, column1, column2 } = data
      this.setData({
        swiper,
        middle,
        column1_title,
        column1,
        column2_title,
        column2
      })
      if (column1 && column1.length > 0) {
        this.setData({
          column1_index: column1[0].id
        })
      }
      if (column2 && column2.length > 0) {
        this.setData({
          column2_index: column2[0].id
        })
      }

    })
  },

  handleSwiper(e) {
    const item = e.currentTarget.dataset.item
    // console.log(item)
    if (item && item.url && item.url.length > 1) {
      if (item.tabbar == 0) {
        wx.navigateTo({
          url: item.url
        })
      } else {
        wx.switchTab({
          url: item.url
        })
      }
    }
  },

  handleColumn1(e) {
    const item = e.currentTarget.dataset.item
    if (item.id != this.data.column1_index) {
      this.setData({
        click1: true,
        column1_index: item.id
      })
    }
  },

  handleColumn2(e) {
    const item = e.currentTarget.dataset.item
    if (item.id != this.data.column2_index) {
      this.setData({
        click2: true,
        column2_index: item.id
      })
    }
  },

  onShow() {
    const go1 = (i) => {
      if (i > this.data.column1.length) {
        i = 0
      }
      if (!this.data.click1) {
        if (this.data.column1[i]) {
          this.setData({
            column1_index: this.data.column1[i].id
          })
        }
        i++
        setTimeout(() => {
          go1(i)
        }, 5000)
      }
    }
    go1(0)

    const go2 = (i) => {
      if (i > this.data.column2.length) {
        i = 0
      }
      if (!this.data.click2) {
        if (this.data.column2[i]) {
          this.setData({
            column2_index: this.data.column2[i].id
          })
        }
        i++
        setTimeout(() => {
          go2(i)
        }, 5000)
      }
    }
    go2(0)
  }

});
